package com.the4man.cnbdw.listener.socket;

import com.the4man.cnbdw.cache.DeviceCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;

/**
 * Created by lenovo on 2017/12/12.
 */
public class UdpSocketThread extends Thread {
    private Logger log = LoggerFactory.getLogger(UdpSocketThread.class);
    private UdpServerSocket serverSocket = null;
    private WebApplicationContext ctx = null;
    private DeviceCache deviceCache = null;

    public UdpSocketThread(UdpServerSocket serverScoket, WebApplicationContext ctx) {
        try {
            if(this.serverSocket == null) {
                this.ctx = ctx;
                this.deviceCache = (DeviceCache)ctx.getBean("deviceCache");
                this.serverSocket = new UdpServerSocket("0.0.0.0", 8889);
                this.log.info("udp socket start");
            }
        } catch (Exception var4) {
            this.log.error("SocketThread创建socket服务出错");
            var4.printStackTrace();
        }

    }

    public void run() {
        while(!this.isInterrupted()) {
            try {
                byte[] bytes = this.serverSocket.receiveBytes();
                (new UdpSocketOperate(bytes, this.deviceCache)).run();

                try {
                    Thread.sleep(30L);
                } catch (Exception var3) {
                    var3.printStackTrace();
                }
            } catch (Exception var4) {
                var4.printStackTrace();
            }
        }

    }

    public void closeSocketServer() {
        try {
            if(this.serverSocket != null) {
                this.serverSocket.close();
                this.serverSocket = null;
            }
        } catch (Exception var2) {
            this.log.error(var2.getMessage(), var2);
        }

    }
}
